<template>
  <el-scrollbar>
    <div v-if="!isKeySet" style="position: relative">
      <div class="full" v-if="base64Png===''">
        请按下 <strong style="color:orange;">ALT+Q</strong> 后，
        按住拖拽 或 单击<strong style="color:orange;">中键（MOUSE3）</strong>截取图片翻译
      </div>
      <el-select v-if="base64Png===''" v-model="ocrLang" @change="ChooseOCRLang" >
        <el-option v-for="item in langs" :label="item" :value="item" />
      </el-select>
      <div class="contain" v-else>
        <img :class="['screen-shot',{'full-screen':isFull}]" @click="FullScreen()"
             :src="'data:image/png;base64,'+base64Png" alt="SCREEN SHOT" ref="imageRef"
             @mousedown.middle="startDrawing" @mousemove="drawRect" @mouseup.middle="stopDrawing"/>
        <div class="after-img">点击选择</div>
        <div class="unit">
          <strong>原文</strong>
        </div>
        <div class="unit">
          <strong>译至：</strong>
          <el-select v-model="transLang" @change="ChooseTransLang" style="width: 80px">
            <el-option v-for="item in langs" :label="item" :value="item" />
          </el-select>
        </div>
        <div class="opts">
          <el-select v-model="ocrLang" @change="ChooseOCRLang" >
            <el-option v-for="item in langs" :label="item+'识图'" :value="item"/>
          </el-select>
        </div>
      </div>
      <div class="contain" v-for="(_,idx) in wordsArr" :key="idx">
        <div class="unit"> <el-input v-model="wordsArr[idx]" /> </div>
        <div class="unit"> <el-input v-model="transArr[idx]" disabled /> </div>
        <div class="opts">
          <el-button type="success" @click="singleTrans(idx)">翻译</el-button>
        </div>
      </div>
      <!--  画布  -->
      <canvas v-if="imageRef&&isFull" ref="canvasRef" :height="imageRef.height" :width="imageRef.width"></canvas>
    </div>
    <div class="mid" v-else>
      <el-input v-model="apiKey" placeholder="Api Key" style="margin-bottom: 10px"/>
      <el-input v-model="secretKey" placeholder="Secret Key" style="margin-bottom: 10px"/>
      <el-button type="success" @click="KeySet()">提交</el-button>
      <br />
      <p>没有密钥？<a target="_blank" href="https://login.bce.baidu.com">点击</a>获取</p>
    </div>
  </el-scrollbar>
</template>

<script lang="ts" setup>
  import {GetLangs, GetLang, SetKey, SetOCRLang, SetWordsLang, SetTransLang, CustomTrans, CustomShot} from "../wailsjs/go/main/App";
  import {WindowShow,WindowFullscreen,WindowUnfullscreen,EventsOn} from "../wailsjs/runtime"
  import {onMounted, ref} from "vue";

  // ------------------------------- API -------------------------------

  let apiKey = ref("") // 百度 API Key
  let secretKey = ref("") // 百度 Secret Key
  let isKeySet = ref(true)

  // 设置
  function KeySet() {
    SetKey(apiKey.value, secretKey.value).then(res => {
      if (res) {
        localStorage.setItem("api", apiKey.value)
        localStorage.setItem("secret", secretKey.value)
        isKeySet.value = false
      } else {
        localStorage.clear()
        isKeySet.value = true
      }
    })
  }

  // ------------------------------- 翻译 -------------------------------

  let base64Png = ref("") // base64 png
  let wordsArr = ref<string[]>([]) // 原文列表
  let transArr = ref<string[]>([]) // 译文列表

  let ocrLang = ref("") // 图像语言
  let wordsLang = ref("") // 原文语言
  let transLang = ref("") // 译文语言
  let langs = ref<string[]>([]) // 语言候选

  // 单个翻译
  function singleTrans(idx:number) {
    CustomTrans(wordsArr.value[idx]).then(res => {
      transArr.value[idx] = res
    }).catch(err => {
      console.log(err)
    })
  }

  // 设置图像识别语言
  function ChooseOCRLang(event:string) {
    SetOCRLang(event)
  }
  // 设置原文语言
  function ChooseWordsLang(event:string) {
    SetWordsLang(event)
  }
  // 设置译文语言
  function ChooseTransLang(event:string) {
    SetTransLang(event)
  }

  // ------------------------------- 全屏 -------------------------------

  let isFull = ref(false)

  // 全屏查看大图（开始框选子图功能）
  function FullScreen() {
    if (isFull.value == false)
      WindowFullscreen()
    isFull.value = true

    if (imageRef.value){
      canvasHeight.value = imageRef.value.height * devicePixelRatio
      canvasWidth.value = imageRef.value.width * devicePixelRatio
    }
  }
  // 取消全屏
  function UnFullScreen() {
    if (!isFull.value)
      return
    WindowUnfullscreen()
    isFull.value = false
    const canvasElement = canvasRef.value;
    if (canvasElement && context.value)
      context.value.clearRect(0, 0, canvasElement.width, canvasElement.height);
  }

  // ------------------------------- 框选 -------------------------------

  // const containerRef:any = ref(null);
  const imageRef = ref<HTMLImageElement | null>(null);
  const canvasRef = ref<HTMLCanvasElement | null>(null);
  const context = ref<CanvasRenderingContext2D | null>(null);
  const isDrawing = ref(false);
  const startX = ref(0);
  const startY = ref(0);
  const devicePixelRatio = window.devicePixelRatio || 1; // TODO 这里可能出现不同分辨率设备问题
  const canvasHeight = ref(0)
  const canvasWidth = ref(0)


  // 框选开始（中键按下）
  function startDrawing(event:MouseEvent) {
    if(!isFull.value)
      return
    if (event.button === 1) {
      const canvasElement = canvasRef.value;
      if (canvasElement) {
        context.value = canvasElement.getContext('2d');
        isDrawing.value = true;
        startX.value = event.offsetX;
        startY.value = event.offsetY;
      }
    }
  }
  // 框选过程（中键拖拽）
  function drawRect(event:MouseEvent) {
    if(!isFull.value)
      return
    if (isDrawing.value && context.value) {
      const canvasElement = canvasRef.value;
      if (canvasElement) {
        const width = event.offsetX - startX.value;
        const height = event.offsetY - startY.value;

        context.value.clearRect(0, 0, canvasElement.width, canvasElement.height);
        context.value.strokeStyle = 'red';
        context.value.lineWidth = 2;
        context.value.strokeRect(startX.value, startY.value, width, height);
      }
    }
  }
  // 框选结束（中键松开）
  function stopDrawing(event:MouseEvent) {
    if(!isFull.value)
      return
    if (isDrawing.value) {
      isDrawing.value = false;
    }

    console.log(startX.value, startY.value, event.offsetX-startX.value, event.offsetY-startY.value)
    CustomShot(startX.value, startY.value, event.offsetX-startX.value, event.offsetY-startY.value, base64Png.value)
  }

  // ------------------------------- 绑定 -------------------------------

  // 截图解析完成
  EventsOn("ShotComplete", (screen_shot:string, result:[string,string][]) => {
    if(screen_shot !== "") {
      base64Png.value = screen_shot
    }
    console.log(result)
    wordsArr.value = result[0]
    transArr.value = result[1]
    console.log(wordsArr,transArr)
    UnFullScreen()
    WindowShow()
  })


  // 绑定 Esc （退出全屏）
  document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
      UnFullScreen()
    }
  });
  // 绑定 Mouse3 （取消原生事件）
  document.addEventListener("mousedown", function(mouseEvent) {
    if (mouseEvent.button != 1) {
      return;
    }
    mouseEvent.preventDefault();
    mouseEvent.stopPropagation();
  });

  // ------------------------------- 初始化 -------------------------------

  onMounted(() => {
    // 配置初始设置
    let api = localStorage.getItem("api")
    let secret = localStorage.getItem("secret")
    if (api != null)
      apiKey.value = api
    if (secret != null)
      secretKey.value = secret
    isKeySet.value = !(apiKey.value !== '' && secretKey.value !== '')
    if (!isKeySet.value) {
      KeySet()
    }
    GetLangs().then(res => {
      langs.value = res
    })
    GetLang().then(res => {
      ocrLang.value = res[0]
      wordsLang.value = res[1]
      transLang.value = res[2]
    })
  })
</script>

<style lang="scss">
  .mid {
    width: 60vw;
    height: 60vh;
    margin: auto;
    padding: 30px;
  }
  .full {
    width: 100vw;
    height: 80vh;
    font-size: 20px;
    /*font-weight: 800;*/
    line-height: 80vh;
    text-align: center;
    user-select: none;
  }
  .contain {
    width: 100vw;
    font-size: 14px;
    display: block;
  }
  .opts {
    width: calc(20vw - 60px);
    height: 30px;
    margin: 0;
    padding: 10px;
    display: inline-block;
    line-height: 30px;
    border-top: gray 2px ridge;
  }
  .unit {
    float: left;
    width: 40vw;
    height: 30px;
    margin: 0;
    padding: 10px;
    display: inline-block;
    line-height: 30px;
    border-top: gray 2px ridge;
  }
  .screen-shot {
    margin: auto auto 10px;
    display: block;
    height: 200px;
    max-height: 200px;
    max-width: calc(100% - 6px);
    transition: all 0.25s;
    border: #6b635b 3px dotted;
    border-radius: 20px;
    &:hover {
      height: 250px;
      max-height: 250px;
      border-radius: 3px;
      opacity: 0.5;
      & + .after-img {
        color: rgba(255, 255, 255, 0.8);
      }
    }
    &.full-screen {
      width: calc(100% - 6px);
      max-height: unset;
      height: auto;
      border: unset;
      border-radius: unset;
      -webkit-user-drag: none;
      &:hover {
        opacity: 1;
      }
    }
  }
  .after-img {
    z-index: -1;
    color: rgba(255, 255, 255, 0);
    font-weight: 800;
    font-size: 20px;
    position: absolute;
    top: 120px;
    text-align: center;
    width: 100%;
    transition: all 0.25s 0.25s;
  }

  canvas {
    z-index: 10;
    background-color: rgba(0, 0, 0, 0.2);
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: none;
  }
</style>
